package com.kurancy.service;

import java.sql.Date;

import javax.persistence.TypedQuery;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kurancy.domain.KurancyCreated;
import com.kurancy.domain.KurancyHistory;
import com.kurancy.domain.KurancyUser;
import com.kurancy.domain.enums.KurancyStatus;
import com.kurancy.web.authentication.service.AuthService;

@Service
public class KurancyNoteServiceImpl implements KurancyNoteService {
	
	@Autowired
	private AuthService authService;
	
    @Autowired
    KurancyUserAction kurancyUserAction;
	
	/** The logger. */
	private static Log logger = LogFactory.getLog(KurancyNoteServiceImpl.class);

	synchronized String generateKurancyToken(String token) {
		
//		MessageDigest md;
//		md = MessageDigest.getInstance("MD5");
//		
//		long time = System.currentTimeMillis();
//		String combined = (token + time);
//
//		md.update(combined.getBytes());
//
//		byte byteData[] = md.digest();
//		
//		//convert the byte to hex format method 1
//		 StringBuffer sb = new StringBuffer();
//		 for (int i = 0; i < byteData.length; i++) {
//		  sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
//		 }
//
//		 return sb.toString();
		return RandomStringUtils.random(8, true, true);
	}

	@Override
	public void generateKurancyNotePage(int numberOfNotes, 
										KurancyCreated templateKurancyCreated, 
										KurancyUser kurancyUser) throws Exception {
		 Date now = new Date(System.currentTimeMillis());
		 
		 for (int i=0; i < numberOfNotes; i++) {
			 KurancyCreated newKurancy = new KurancyCreated();
			newKurancy.setAmount(templateKurancyCreated.getAmount());
	     	   //set fields not shown on form
			newKurancy.setCreatedOn(now);
			newKurancy.setCreatedBy(kurancyUser.getFacebookUserId());
			
			newKurancy.setKurancyToken(generateKurancyToken(templateKurancyCreated.getCreatedBy()));
			KurancyHistory history = new KurancyHistory();
			history.setCreatedOn(now);
			history.setDescription("Kurancy created by user");
			history.setStatus(KurancyStatus.ACTIVE);
			newKurancy.getKuruancyHistories().add(history);

			kurancyUserAction.saveKurancyCreated(newKurancy);
			logger.debug("kurancy created with token value: " + newKurancy.getKurancyToken());
		 }
		
	}

	@Override
	public void markNotePaid(String payKey) {
		 Date now = new Date(System.currentTimeMillis());
		 
		 TypedQuery<KurancyCreated> createdQuery = KurancyCreated.findKurancyCreatedsByPaypalPayKeyEquals(payKey);
		 KurancyCreated created = createdQuery.getSingleResult();
		 if (created != null) {
			 created.setStatus(KurancyStatus.COMPLETED);
			 KurancyHistory history = new KurancyHistory();
			 history.setCreatedOn(now);
			 history.setDescription("Kurancy Paid by Paypal Pay Key: " + payKey);
			 history.setStatus(KurancyStatus.COMPLETED);
			 
			 created.getKuruancyHistories().add(history);
			 created.flush();
		 }
	}

	@Override
	public void markNoteCancelled(String payKey) {
		Date now = new Date(System.currentTimeMillis());
		 
		 TypedQuery<KurancyCreated> createdQuery = KurancyCreated.findKurancyCreatedsByPaypalPayKeyEquals(payKey);
		 KurancyCreated created = createdQuery.getSingleResult();
		 if (created != null) {
			 created.setStatus(KurancyStatus.ERRORED);
			 KurancyHistory history = new KurancyHistory();
			 history.setCreatedOn(now);
			 history.setDescription("Kurancy Errored by Paypal Pay Key: " + payKey);
			 history.setStatus(KurancyStatus.ERRORED);
			 
			 created.getKuruancyHistories().add(history);
			 created.flush();
		 }
	}

	@Override
	public void markNoteClaimed(String kurancyToken) {
		Date now = new Date(System.currentTimeMillis());
		KurancyUser user = authService.getKurancyUser();
		 
		 TypedQuery<KurancyCreated> createdQuery = KurancyCreated.findKurancyCreatedsByKurancyTokenEquals(kurancyToken);
		 KurancyCreated created = createdQuery.getSingleResult();
		 if (created != null) {
			 created.setStatus(KurancyStatus.CLAIMED);
			 KurancyHistory history = new KurancyHistory();
			 history.setCreatedOn(now);
			 history.setDescription("Kurancy Claimed by User: " + user.getFacebookUserId());
			 history.setStatus(KurancyStatus.CLAIMED);
			 
			 created.getKuruancyHistories().add(history);
			 created.flush();
		 }
		
	}
}